import request from '@/axios'
import { check } from './baseModel'
import { Arrayable } from 'element-plus/es/utils'
import { FormItemRule, UploadRawFile } from 'element-plus'

// 分类 model
export interface Category {
    id: string              // ID
    name: string            // 名称
    description: string     // 描述
    status: boolean         // 是否激活
    productCount: number    // 分类其下的商品数
    image: string
}

// 分了用于提交的表单格式（主要用于修改操作）
export interface CategoryForm {
    id: string
    name: string            // 名称
    description: string     // 描述
    status: boolean         // 是否激活

    image: UploadRawFile | undefined | string
}

// 表单的校验格式
export const categoryFormRules: Partial<Record<string, Arrayable<FormItemRule>>> = {
    name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入描述', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    image: [
        { required: true, message: '请上传商品图片', trigger: 'change' }
    ]
}

export function getInitCategoryForm() {
    return {
        id: '',
        name: '',
        description: '',
        status: true,
        image: undefined
    }
}

/**
 * 用于发起分类请求的 API
 *  static getAll()                         获取所有数据
 *  static create(Form)                     新增数据
 *  static deleteById(id)                   删除数据
 *  static updateById(Form, id)             修改数据
 */
export class CategoryApi {
    static baseUrl = "/category"

    // 获取所有数据
    static async getAll(): Promise<Category[]> {
        try {
            const response = await request.get(
                this.baseUrl,
                { data: { loading: '获取分类数据' } }
            );
            return check(response) as Category[]
        }
        catch (error: any) { throw error }
    }

    // 新增数据
    static async create(form: CategoryForm) {
        try {
            let data = new FormData()
            for (let item in form) { data.append(item, form[item]) }
            const response = await request.post(
                this.baseUrl,
                data,
                { headers: { 'Content-Type': 'multipart/form-data' } }
            )
            return check(response) as Category;
        }
        catch (error: any) { throw error }
    }

    // 删除数据
    static async deleteById(id: string) {
        try {
            const response = await request.delete(
                `${this.baseUrl}/${id}`,
                { data: { loading: '删除分类' } }
            )
            check(response)
        }
        catch (error: any) { throw error }
    }

    // 修改数据
    static async updateById(form: Category | CategoryForm, id: string): Promise<Category> {
        try {

            let data = new FormData()
            for (let item in form) { data.append(item, form[item]) }
            if (form.image == undefined || typeof form.image == 'string')
                data.delete("image")

            const response = await request.put(
                `${this.baseUrl}/${id}`,
                data,
                { headers: { 'Content-Type': 'multipart/form-data' } }
            );

            return check(response) as Category
        }
        catch (error: any) { throw error }
    }
} 